﻿using D.B.Data.API.Applications.Command.RoleMenusCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace D.B.Data.API.Applications.CommandHandler.RoleMenusCommandHandler
{
    public class AddRoleMenusCommandHandler : IRequestHandler<AddRoleMenusCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleMenusModel> baseRepository;
        private readonly DataDbContext dbContext;

        public AddRoleMenusCommandHandler(IBaseRepository<RoleMenusModel> baseRepository, DataDbContext dbContext)
        {
            this.baseRepository = baseRepository;
            this.dbContext = dbContext;
        }

        public Task<APIResult<int>> Handle(AddRoleMenusCommand request, CancellationToken cancellationToken)
        {
            // 获取同步执行策略（关键：用Execute而非ExecuteAsync）
            var executionStrategy = dbContext.Database.CreateExecutionStrategy();

            // 执行同步事务逻辑
            var result = executionStrategy.Execute(() =>
            {
                int count = 0;
                using var transaction = dbContext.Database.BeginTransaction(); // 同步开启事务
                try
                {

                    var list = request.MId.Split(',').ToList();

                    var rolemenuQuery = baseRepository.GetAll().Where(s => s.RID == request.RId);

                    count += baseRepository.Del(rolemenuQuery.ToList());

                    List<RoleMenusModel> model = new List<RoleMenusModel>();
                    foreach (var item in list)
                    {
                        if (Convert.ToInt64(item) == 0) continue;

                        model.Add(new RoleMenusModel
                        {
                            MID = Convert.ToInt64(item),
                            RID = request.RId
                        });
                    }
                    count += baseRepository.Add(model);


                    transaction.Commit();
                    return new APIResult<int>
                    {
                        Code = EnumCode.Ok,
                        Msg = "分配成功"
                    };

                }
                catch (Exception ex)
                {
                    transaction.Rollback(); // 同步回滚
                    return new APIResult<int>
                    {
                        Code = EnumCode.Ok,
                        Msg = $"分配失败：{ex.Message}"
                    };
                }
            });

            // 将同步结果包装为Task返回（因接口要求返回Task）

            // 5. 提交事务
            
            return Task.FromResult(result);
        }


    }
}
//        APIResult<int> aPIResult = new APIResult<int>();
//            int count = 0;

//            using (var tran= baseRepository.Context.Database.BeginTransaction())
//            {
//                try
//                {
                    
//                    var list=request.MId.Split(',').ToList();

//                    var rolemenuQuery = baseRepository.GetAll().Where(s => s.RID == request.RId);

//                    count+=baseRepository.Del(rolemenuQuery.ToList());

//                    List<RoleMenusModel> model = new List<RoleMenusModel>();
//                    foreach (var item in list)
//                    {
//                        if (Convert.ToInt64(item) == 0) continue;

//                        model.Add(new RoleMenusModel
//                        {
//                            MID = Convert.ToInt64(item),
//                            RID = request.RId
//                        });
//                    }
//                    count+=baseRepository.Add(model);


//                    tran.Commit();
//                }
//                catch (Exception ex)
//                {
//                    tran.Rollback();
//                    throw;
//                }



//            }

//            aPIResult.Data = count;
//            if (count > 0 )
//            {
//                aPIResult.Code=EnumCode.Ok;
//                aPIResult.Msg = "保存成功";
//            }
//            else
//            {
//                aPIResult.Code = EnumCode.Ok;
//                aPIResult.Msg = "保存成功";
//            }

//            return Task.FromResult(aPIResult);
//        }
//    }
//}
